package com.dingding.order.core.publish.dao.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.daox.ISQLBaseDao;
import com.dingding.common.core.base.daox.impl.CriteriaBaseDaoImpl;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.special.UserspecialorderT;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.GetDistanceUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.dto.CalculatDistanceDTO;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.order.core.publish.dao.IPublishSpecialOrderDao;
import com.dingding.order.core.publish.sql.PublishSpecialOrderSQL;
import com.dingding.order.dto.publish.special.ReqPublishOrderDTO;
import com.dingding.order.dto.publish.special.ResPublishOrderDTO;

/**
 * 
 * @ClassName: PublishSpecialOrderDaoImpl
 * @Description: 发布专车订单DAO实现类
 * @author YHQ
 * @date 2016年8月23日 下午2:43:14
 * @since V2.4.0
 * 
 */
@Component("publishSpecialOrderDao")
public class PublishSpecialOrderDaoImpl implements IPublishSpecialOrderDao {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "criteriaBaseDao")
	private CriteriaBaseDaoImpl criteriaBaseDao;

	@Resource(name = "SQLBaseDao")
	private ISQLBaseDao sqlBaseDao;

	@Resource(name = "queueFacade")
	private IQueueFacade queueFacade;

	/**
	 * 
	 * @Title: getUserSpecialOrdertList
	 * @Description: 根据用户Id获取其未完成订单列表
	 * @param userId
	 *            用户Id
	 * @author YHQ
	 * @return List<Userspecialordert> 返回类型
	 * 
	 */
	@Override
	@Transactional(readOnly = true)
	public List<UserspecialorderT> getUserSpecialOrdertList(String userId) {

		Criterion criterion = Restrictions.eq("placeOrderUserId", userId);

		try {
			return criteriaBaseDao.queryCriteriaList(UserspecialorderT.class, criterion);
		} catch (Exception e) {
			log.error("根据用户Id获取其未完成订单列表时出现异常   类：" + this.getClass() + " getUserSpecialOrdertList()", e);
		}

		return null;
	}

	/**
	 * 
	 * @Title: releaseOrder
	 * @Description: 发布订单操作
	 * @param reqPublishOrderDTO
	 *            待发布的订单信息
	 * @author YHQ
	 * @return boolean 返回类型
	 * 
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
	public UserspecialorderT releaseOrder(ReqPublishOrderDTO reqPublishOrderDTO) {

		// 订单临时表对象
		UserspecialorderT userspecialordert = new UserspecialorderT();
		Integer vehicleLevelId = reqPublishOrderDTO.getVehicleLevelId();
		//为兼容线上版本，当没有车辆等级时。默认为经济型
		if (vehicleLevelId == null) {
			vehicleLevelId = 1;
		}
		// 车辆类型ID
		userspecialordert.setVehicleLevelId(vehicleLevelId);
		// 订单里程
		userspecialordert.setEstimateDistance(reqPublishOrderDTO.getDistance());
		// 目的地
		userspecialordert.setEndAddress(reqPublishOrderDTO.getEndAddress());
		// 目的地纬度
		userspecialordert.setEndLatitude(reqPublishOrderDTO.getEndLatitude());
		// 目的地经度
		userspecialordert.setEndLongitude(reqPublishOrderDTO.getEndLongitude());
		// 出发类型 1:实时 2:预约
		userspecialordert.setSetOutType(reqPublishOrderDTO.getSetOutType());
		// 下单人
		userspecialordert.setPlaceOrderUserId(reqPublishOrderDTO.getPlaceOrderUserId());
		// 出发时间
		if (reqPublishOrderDTO.getSetOutType() == 2) {
			userspecialordert.setSetOutTime(DateFormatUtil.yyyy_MM_dd_HHmmss(reqPublishOrderDTO.getSetOutTime()));
		} else {
			userspecialordert.setSetOutTime(new Date());
		}

		// 起点地址
		userspecialordert.setStartAddress(reqPublishOrderDTO.getStartAddress());
		// 起点纬度
		userspecialordert.setStartLatitude(reqPublishOrderDTO.getStartLatitude());
		// 起点经度
		userspecialordert.setStartLongitude(reqPublishOrderDTO.getStartLongitude());
		// 平台估算金额
		userspecialordert.setEstimateMoney(reqPublishOrderDTO.getTotalMoney());

		// 订单Id
		userspecialordert.setSpecialOrderId(ToolUtil.getUid());
		// 下单时间
		userspecialordert.setCreateTime(new Date());

		// 获取下单城市
		CalculatDistanceDTO calculatDistanceDTO = GetDistanceUtil.getSingleDistance(
				reqPublishOrderDTO.getStartLongitude(), reqPublishOrderDTO.getStartLatitude(),
				reqPublishOrderDTO.getEndLongitude(), reqPublishOrderDTO.getEndLatitude());

		// 下单城市
		userspecialordert.setPlaceOrderCity(calculatDistanceDTO.getCityName());
		// 发单类型
		userspecialordert.setPublishType(3);
		// 订单状态
		userspecialordert.setOrderStatus(1);
		// 城市编码
		userspecialordert.setPlaceOrderCityCode(calculatDistanceDTO.getCityNo());
		// 预估订单时长
		userspecialordert.setEstimateDuration(calculatDistanceDTO.getEstimateDuration());

		try {
			criteriaBaseDao.save(userspecialordert);
		} catch (Exception e) {
			log.error("将订单信息保存到数据库时出现异常   类：" + this.getClass() + " releaseOrder", e);
			return null;
		}

		return userspecialordert;
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
	public void addSpecialOrderToQueue(ResponseEntity<ResPublishOrderDTO> response,
			UserspecialorderT userspecialordert) {

		// 发布订单响应Bean
		ResPublishOrderDTO resPublishOrderDTO = new ResPublishOrderDTO();

		// 下单时间
		resPublishOrderDTO.setCrearTime(userspecialordert.getCreateTime());
		// 订单Id
		resPublishOrderDTO.setOid(userspecialordert.getSpecialOrderId());
		// 发单类型
		resPublishOrderDTO.setPublishType(userspecialordert.getPublishType());
		// 出发时间
		resPublishOrderDTO.setSetOutTime(userspecialordert.getSetOutTime());
		// 出发时间标准格式
		ResPublishOrderDTO publishOrderDTO = sqlBaseDao.sqlToCustomBeanUnique(ResPublishOrderDTO.class,
				PublishSpecialOrderSQL.PUBLISH_SPECIAL_ORDER, userspecialordert.getVehicleLevelId());

		if (publishOrderDTO != null) {
			resPublishOrderDTO.setOutTime(DateFormatUtil.getMMddEHHss(resPublishOrderDTO.getSetOutTime()) + " "
					+ publishOrderDTO.getVehicleLevelName());
		}

		// 发布订单响应码
		response.setCode(HttpStatus.SC_OK);
		// 响应参数
		response.setResponseBody(resPublishOrderDTO);

		// 加入队列
		assignOrder(userspecialordert);
	}

	/**
	 * 
	 * @Title: assignOrder
	 * @Description: 指派订单操作
	 * @param oid
	 *            订单Id
	 * @author YHQ
	 * @return void 返回类型
	 * 
	 */
	public void assignOrder(UserspecialorderT userspecialordert) {

		this.queueFacade.addSpecialOrderToQueue(userspecialordert);
	}

}
